import { createSlice } from '@reduxjs/toolkit'
import { getToken, removeToken, setToken as _setToken } from '@/utils/token.js'

const userSlice = createSlice({
  name: 'user',
  // 数据状态
  initialState: {
    token: getToken() || '',
    userInfo: {}
  },
  // 同步方法
  reducers: {
    /**
     * 设置用户信息
     * @param state
     * @param action
     */
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },

    /**
     * 删除用户信息
     * @param state
     */
    removeUserInfo(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    },

    /**
     * 设置用户token
     * @param state
     * @param action
     */
    setToken(state, action) {
      state.token = action.payload
      _setToken(action.payload)
    }
  }
})

export const { setUserInfo, removeUserInfo, setToken } = userSlice.actions
export default userSlice.reducer
